<route lang="jsonc">{
    "style": {
        "navigationBarTitleText": "产品详情",
        "navigationBarBackgroundColor": "#ffa622",
        "navigationBarTextStyle": "white"
    }
}</route>

<script lang="ts" setup>
import { onLoad } from '@dcloudio/uni-app'
import { computed, ref, watch } from 'vue'
import { addLoanApplication, loanCalc, useVerify, viewBankInfo, corporateAuthInfo } from '@/api/user' // 添加 viewBankInfo 导入
import ImageUpload from '@/components/ImageUpload.vue' // 导入图片上传组件

// 产品详情数据
const productDetail = ref({
    tp: '', // 对应 tp 字段
    description: '让您的创业更轻松',
    quota: '', // 对应 quota 字段，显示时需要转换为万元
    annual_interest_rate: '', // 对应 annual_interest_rate 字段
    installment_periods: '', // 根据 min_term 和 high_term 组合显示
    limit: 0, // 添加 limit 字段：0 不限制，1 企业配资，2 个人配资
    conditions: [
        '家乐在职3年及以上',
        '自有经营房源10套及以上',
        '参与公司合伙人项目1个及以上',
        '公司认证团队长且团队人数达50人及以上',
    ],
    // 完整的产品信息字段
    id: '',
    term: 0,
    company_id: '',
    created_time: '',
    creator_name: '',
    creator_tel: '',
    high_term: '',
    min_term: '',
    monthly_interest_rate: '',
    name: '',
    repayment_account: '',
    status: '',
})
const userTel = uni.getStorageSync('user') ? JSON.parse(uni.getStorageSync('user')).userInfo.telephone : ''
const isCs = !userTel || userTel == '18373481952'
// 控制弹窗显示
const showModal = ref(false)

// 控制配资信息弹窗显示
const showLoanModal = ref(false)

// 配资信息表单数据
const loanForm = ref({
    product_id: '',
    bank_name: '',
    sale_company_id: '',
    bank_user: '',
    bank_no: '',
    description: '',
    boss_pics: '',
    principal: '', // 配资额度
    installment_periods: 12, // 配资期限
    loan_class: 1, // 配资类型 1 企业配资 2 个人配资
    repayment_method: 1, // 还款形式 1 分期还款 2 利润分成
})

// 利息计算结果
const loanCalcResult = ref({
    total_interest: 0, // 利息合计
    total_repayment_amount: 0, // 累计还款
    repayment_amount: 0, // 每期还款
})

// 防抖定时器
let debounceTimer: NodeJS.Timeout | null = null

// 利息计算函数
async function calculateLoanInterest(principal: string | number, periods: number) {
    if (!principal || !loanForm.value.product_id || !periods) {
        // 如果参数不完整，重置计算结果
        loanCalcResult.value = {
            total_interest: 0,
            total_repayment_amount: 0,
            repayment_amount: 0,
        }
        return
    }

    try {
        const result = await loanCalc({
            product_id: Number(loanForm.value.product_id),
            principal: Number(principal),
            periods: Number(periods),
        })
        console.log(result)
        loanCalcResult.value = {
            total_interest: result.total_interest || 0,
            total_repayment_amount: result.total_repayment_amount || 0,
            repayment_amount: result.repayment_amount || 0,
        }
    }
    catch (error) {
        // console.error('计算利息失败:', error)
        // 重置计算结果
        loanCalcResult.value = {
            total_interest: 0,
            total_repayment_amount: 0,
            repayment_amount: 0,
        }
    }
}

// 监听借款额度和期数变化，使用防抖自动计算利息
watch([() => loanForm.value.principal, () => loanForm.value.installment_periods], ([principal, periods]) => {
    // 清除之前的定时器
    if (debounceTimer) {
        clearTimeout(debounceTimer)
    }
    // 设置新的防抖定时器，500ms后执行
    debounceTimer = setTimeout(() => {
        calculateLoanInterest(principal, periods)
    }, 500)
}, { immediate: false })

function handleApply() {
    showModal.value = true
}

function closeModal() {
    showModal.value = false
}

async function confirmApply() {
    if (loanForm.value.loan_class === 1) {
        // 获取企业认证信息
        const useInfo = await corporateAuthInfo()
        if (!useInfo) {
            uni.showToast({
                title: '请完善企业资料',
                icon: 'none',
            })
            setTimeout(() => {
                uni.navigateTo({
                    url: '/pages-sub/userInfo/companyAudit',
                })
            }, 1500)
            return
        } else {
            const { bank_name, bank_user, bank_no, company_id } = useInfo
            loanForm.value.bank_name = bank_name || ''
            loanForm.value.bank_user = bank_user || ''
            loanForm.value.bank_no = bank_no || ''
            loanForm.value.sale_company_id = company_id
        }

    }
    else {
        // getBank()
        // 获取实名认证信息
        const useInfo = await useVerify()
        console.log('useInfo:', useInfo.data)
        if (!useInfo.data.identifyFront) {
            uni.showToast({
                title: '请完善实名认证信息',
                icon: 'none',
            })
            setTimeout(() => {
                uni.navigateTo({
                    url: '/pages-sub/userInfo/authentication',
                })
            }, 1500)
            return
        }
        // 获取银行信息
        const res = await viewBankInfo()
        if (res.length === 0) {
            uni.showToast({
                title: '请先添加银行卡',
                icon: 'none',
            })
            setTimeout(() => {
                uni.navigateTo({
                    url: '/pages-sub/userInfo/bankCard',
                })
            }, 1500)
            return
        }
        const { bank_name, bank_user, bank_no } = res[res.length - 1]
        loanForm.value.bank_name = bank_name || ''
        loanForm.value.bank_user = bank_user || ''
        loanForm.value.bank_no = bank_no || ''
        loanForm.value.sale_company_id = ''
        // 获取实名认证信息
    }
    showModal.value = false
    showLoanModal.value = true
}

// 优化获取银行信息函数
async function getBank() {
    if (isCs) return
    try {
        const res = await viewBankInfo()
        if (res && res.length > 0) {
            const { bank_name, bank_user, bank_no } = res[res.length - 1]
            loanForm.value.bank_name = bank_name || ''
            loanForm.value.bank_user = bank_user || ''
            loanForm.value.bank_no = bank_no || ''
        }
        else {
            // 没有银行卡信息时的处理
            uni.showToast({
                title: '请先登录并完善信息',
                icon: 'none',
            })
        }
    }
    catch (error) {
        console.error('获取银行信息失败:', error)
        uni.showToast({
            title: '获取银行信息失败',
            icon: 'none',
        })
    }
}

const periodOptions = [12, 24, 36]

// 添加以下代码
const showPeriodSheet = ref(false)

// 将 periodOptions 转换为 action-sheet 需要的格式
const periodActions = computed(() => {
    return periodOptions.map(option => ({
        name: `${option}个月`,
        value: option,
    }))
})

// 显示期限选择器
function showPeriodActionSheet() {
    showPeriodSheet.value = true
}

// 选择期限
function onPeriodSelect(action) {
    loanForm.value.installment_periods = action.item.value
    console.log(action)

    showPeriodSheet.value = false
}
// 添加还款形式选择相关代码
const showRepaymentSheet = ref(false)

// 还款形式选项
const repaymentOptions = [
    { name: '分期还款', value: 1 },
    { name: '利润分成', value: 2 },
]

// 显示还款形式选择器
function showRepaymentActionSheet() {
    showRepaymentSheet.value = true
}

// 选择还款形式
function onRepaymentSelect(action) {
    loanForm.value.repayment_method = action.item.value
    showRepaymentSheet.value = false
}

// 切换申请类型
function switchApplyType(type: 1 | 2) {
    loanForm.value.loan_class = type
}
// 重置表单时也要重置还款形式
async function submitLoanApplication() {
    console.log(loanForm.value, '提交数据')

    // 验证表单数据
    if (!loanForm.value.principal) {
        uni.showToast({
            title: '请填写配资额度',
            icon: 'none',
        })
        return
    }

    // 验证银行信息
    if (!loanForm.value.bank_user || !loanForm.value.bank_no) {
        uni.showToast({
            title: '请先完善银行卡信息',
            icon: 'none',
        })
        return
    }
    if (!loanForm.value.boss_pics) {
        uni.showToast({
            title: '请上传总经理同意凭证',
            icon: 'none',
        })
        return
    }

    try {
        // 显示加载状态
        uni.showLoading({
            title: '提交中...',
        })
        const data = JSON.parse(JSON.stringify(loanForm.value))
        data.periods = loanForm.value.installment_periods
        const result = await addLoanApplication(data)
        uni.hideLoading()
        uni.showToast({
            title: '申请提交成功',
            icon: 'success',
        })
        // 关闭弹窗
        showLoanModal.value = false
        // 重置表单
        resetForm()
        // 可以跳转到申请结果页面
        uni.switchTab({
            url: '/pages/operation/index',
        })
    }
    catch (error) {
        uni.hideLoading()
    }
}

// 重置表单函数
function resetForm() {
    loanForm.value = {
        principal: '',
        bank_name: '',
        bank_user: '',
        bank_no: '',
        boss_pics: '',
        description: '',
        product_id: productDetail.value.id,
        loan_class: 1,
        sale_company_id: '',
        installment_periods: 12,
        repayment_method: 1,
    }
}
onLoad((options: any) => {
    // 可以通过路由参数获取产品信息
    if (options.productData) {
        try {
            const data = JSON.parse(decodeURIComponent(options.productData))
            // 更新数据映射逻辑
            productDetail.value = {
                ...productDetail.value,
                ...data,
            }
            loanForm.value.product_id = data.id
        }
        catch (e) {
            console.log('解析产品数据失败', e)
        }
    }
})
</script>

<template>
    <view class="container">
        <!-- 头部区域 -->
        <view class="header">
            <view class="header-content">
                <view class="title">
                    {{ productDetail.name }} <!-- 显示产品名称 -->
                </view>
                <template v-if="!isCs">
                    <view class="product-tag">
                        {{ productDetail.tp }}
                    </view>
                    <view class="subtitle">
                        {{ productDetail.description }}
                    </view>
                </template>
            </view>
        </view>

        <!-- 产品详情卡片 -->
        <view class="detail-card">
            <!-- 产品核心信息 -->
            <view class="product-info" v-if="!isCs">
                <view class="info-row">
                    <view class="info-item">
                        <view class="info-value">
                            {{ productDetail.quota }}
                        </view>
                        <view class="info-label">
                            最高配资
                        </view>
                    </view>
                    <view class="info-item">
                        <view class="info-value">
                            {{ productDetail.annual_interest_rate }}% <!-- 显示年利率 -->
                        </view>
                        <view class="info-label">
                            年化利率
                        </view>
                    </view>
                    <view class="info-item">
                        <view class="info-value">
                            {{ `${productDetail.min_term}-${productDetail.high_term}` }}个月 <!-- 显示期限范围 -->
                        </view>
                        <view class="info-label">
                            配资期限
                        </view>
                    </view>
                </view>
            </view>

            <!-- 申请条件 -->
            <view class="conditions-section">
                <view class="section-title">
                    <view class="line" />
                    <text class="title-text">{{ isCs ? '描述' : '申请条件' }}</text>
                    <view class="line" />
                </view>
                <view class="conditions-list">
                    <view v-for="(condition, index) in productDetail.conditions" :key="index" class="condition-item">
                        <text class="condition-text">{{ condition }}</text>
                    </view>
                </view>
            </view>
            <view class="loan-type-tags" v-if="!isCs">
                <view v-if="[0, 1].includes(productDetail.limit)" class="loan-tag enterprise-tag">
                    企业配资
                </view>
                <view v-if="[0, 2].includes(productDetail.limit)" class="loan-tag personal-tag">
                    个人配资
                </view>
                <view :class="['loan-tag', productDetail.term == 1 ? 'short-term-tag' : 'long-term-tag']">
                    {{ productDetail.term == 1 ? '短期' : '长期' }}
                </view>
            </view>
        </view>

        <!-- 底部申请按钮 -->
        <view class="bottom-action" v-if="!isCs">
            <view class="apply-button" @click="handleApply">
                立即申请
            </view>
        </view>

        <!-- 申请弹窗 -->
        <view v-if="showModal" class="modal-overlay" @click="closeModal">
            <view class="modal-content" @click.stop>
                <view class="modal-header">
                    <text class="modal-title">{{ productDetail.tp }}</text>
                </view>

                <view class="modal-body">
                    <view class="info-item">
                        <text class="info-label">最高配资</text>
                        <text class="info-value">{{ productDetail.quota }}</text>
                    </view>

                    <view class="info-item">
                        <text class="info-label">需要进行经营资产审核</text>
                    </view>

                    <view class="tag-section">
                        <view v-if="productDetail.limit === 0 || productDetail.limit == 1" class="tag"
                            :class="{ active: loanForm.loan_class === 1 }" @click="switchApplyType(1)">
                            <text class="tag-text">企业申请</text>
                        </view>
                        <view v-if="productDetail.limit === 0 || productDetail.limit == 2" class="tag"
                            :class="{ active: loanForm.loan_class === 2 }" @click="switchApplyType(2)">
                            <text class="tag-text">个人申请</text>
                        </view>
                    </view>
                </view>

                <view class="modal-footer">
                    <view class="confirm-button" @click="confirmApply">
                        确认申请角色
                    </view>
                </view>
            </view>
        </view>
        <!-- 配资信息填写弹窗 -->
        <wd-popup v-model="showLoanModal" position="center" custom-style="border-radius: 20rpx; width: 85vw;" closable>
            <view class="loan-modal-content">
                <view class="modal-header">
                    <text class="modal-title">请输入配资信息</text>
                </view>
                <wd-cell-group border>
                    <wd-input v-model="loanForm.principal" required label="借款额度" type="digit" placeholder="借款金额"
                        custom-style="flex: 1; --input-font-size: 24px; --input-padding: 0;text-align: right;"
                        no-border />
                    <wd-cell required title="借多久(月)" :value="loanForm.installment_periods" is-link
                        @click="showPeriodActionSheet" />
                    <wd-cell required title="还款形式"
                        :value="repaymentOptions.find(item => item.value === loanForm.repayment_method)?.name" is-link
                        @click="showRepaymentActionSheet" />
                    <wd-cell title="利息合计"
                        :value="loanCalcResult.total_interest ? `￥${loanCalcResult.total_interest.toFixed(2)}` : '￥0.00'" />
                    <wd-cell title="累计还款"
                        :value="loanCalcResult.total_repayment_amount ? `￥${loanCalcResult.total_repayment_amount.toFixed(2)}` : '￥0.00'" />
                    <wd-cell title="每期还款"
                        :value="loanCalcResult.repayment_amount ? `￥${loanCalcResult.repayment_amount.toFixed(2)}` : '￥0.00'" />
                    <wd-cell title="收款账户" :value="`${loanForm.bank_user}-${loanForm.bank_name}${loanForm.bank_no}`" />
                    <!-- 总经理同意凭证上传 -->
                    <wd-cell-group custom-class="upload-cell-group">
                        <view class="upload-container">
                            <ImageUpload v-model="loanForm.boss_pics" upload-text="上传同意凭证" upload-hint="请上传总经理同意凭证照片"
                                icon-type="camera-filled" />
                        </view>
                    </wd-cell-group>
                </wd-cell-group>
                <view class="modal-footer">
                    <wd-button block size="large"
                        custom-style="background-color: #ffa622; border-color: #ffa622; color: #fff;"
                        @click="submitLoanApplication">
                        确认申请
                    </wd-button>
                </view>
            </view>
        </wd-popup>
        <!-- 期限选择器 -->
        <wd-action-sheet v-model="showPeriodSheet" :actions="periodActions" title="选择借款期限" @select="onPeriodSelect" />
        <!-- 还款形式选择器 -->
        <wd-action-sheet v-model="showRepaymentSheet" :actions="repaymentOptions" title="选择还款形式"
            @select="onRepaymentSelect" />
    </view>
</template>

<style>
page {
    background-color: #f7f8fa;
}
</style>

<style lang="scss" scoped>
.container {
    min-height: 100vh;
    padding-bottom: 160rpx;
    background-color: #f7f8fa;
}

.header {
    padding: 40rpx 40rpx 80rpx;
    background: #ffa622;

    .header-content {
        text-align: left;

        .title {
            font-size: 48rpx;
            font-weight: bold;
            color: #ffffff;
            margin-bottom: 16rpx;
        }

        .product-tag {
            display: inline-block;
            background-color: rgba(255, 255, 255, 0.2);
            color: #ffffff;
            font-size: 24rpx;
            padding: 8rpx 16rpx;
            border-radius: 20rpx;
            margin-bottom: 16rpx;
            border: 2rpx solid rgba(255, 255, 255, 0.3);
        }

        .subtitle {
            font-size: 28rpx;
            color: #ffffff;
            opacity: 0.9;
        }
    }
}

.detail-card {
    margin: -40rpx 40rpx 0;
    background: #ffffff;
    border-radius: 16rpx;
    padding: 40rpx;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
    position: relative;
}

.product-info {
    margin-bottom: 50rpx;

    .info-row {
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .info-item {
        text-align: center;
        flex: 1;

        .info-value {
            font-size: 40rpx;
            font-weight: bold;
            color: #333333;
            margin-bottom: 8rpx;
        }

        .info-label {
            font-size: 24rpx;
            color: #666666;
        }
    }
}

.conditions-section {
    margin-bottom: 40rpx;

    .section-title {
        display: flex;
        align-items: center;
        justify-content: center;
        margin-bottom: 30rpx;

        .title-text {
            font-size: 26rpx;
            color: #999999;
            margin: 0 20rpx;
            flex-shrink: 0;
        }

        .line {
            width: 100%;
            height: 1px;
            background-color: #eeeeee;
        }
    }

    .conditions-list {
        .condition-item {
            text-align: center;
            margin-bottom: 20rpx;

            .condition-text {
                font-size: 28rpx;
                color: #555555;
                line-height: 1.5;
            }
        }
    }
}

.loan-type-tags {
    display: flex;
    justify-content: center;
    gap: 20rpx;
    margin-top: 30rpx;
    flex-wrap: wrap;

    .personal-tag {
        background: #e8f4fd;
        color: #1890ff;
    }

    .short-term-tag {
        background: #fff7e6;
        color: #fa8c16;
    }

    .long-term-tag {
        background: #f6ffed;
        color: #52c41a;
    }
}

.loan-tag {
    padding: 10rpx 24rpx;
    border-radius: 30rpx;
    font-size: 24rpx;
    font-weight: bold;
    display: inline-block;
}

.enterprise-tag {
    background: #ffefee;
    color: #fa5151;
}

.personal-tag {
    background: #e8f4fd;
    color: #1890ff;
}

.bottom-action {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background: #ffffff;
    padding: 24rpx 40rpx;
    padding-bottom: calc(24rpx + constant(safe-area-inset-bottom));
    padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
    box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);

    .apply-button {
        background: #ffa622;
        color: #ffffff;
        padding: 28rpx;
        border-radius: 48rpx;
        font-size: 32rpx;
        font-weight: bold;
        text-align: center;

        &:active {
            opacity: 0.9;
        }
    }
}

// 弹窗样式
.modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;
}

.modal-content {
    width: 600rpx;
    background-color: #fff;
    border-radius: 20rpx;
    overflow: hidden;
}

.modal-header {
    padding: 40rpx 40rpx 20rpx;
    text-align: center;

    .modal-title {
        font-size: 36rpx;
        font-weight: bold;
        color: #333;
    }
}

.modal-body {
    padding: 20rpx 40rpx 40rpx;

    .info-item {
        margin-bottom: 30rpx;

        .info-label {
            font-size: 28rpx;
            color: #666;
            display: block;
            margin-bottom: 10rpx;
        }

        .info-value {
            font-size: 32rpx;
            color: #333;
            font-weight: bold;
        }
    }

    .tag-section {
        display: flex;
        gap: 20rpx;
        margin-top: 30rpx;

        .tag {
            flex: 1;
            padding: 20rpx;
            border: 2rpx solid #ddd;
            border-radius: 10rpx;
            text-align: center;

            &.active {
                background-color: #ffa622;
                border-color: #ffa622;

                .tag-text {
                    color: #fff;
                }
            }

            .tag-text {
                font-size: 28rpx;
                color: #666;
            }
        }
    }
}

.modal-footer {
    padding: 0 40rpx 40rpx;

    .confirm-button {
        width: 100%;
        height: 80rpx;
        background-color: #ffa622;
        border-radius: 40rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #fff;
        font-size: 32rpx;
        font-weight: bold;
    }
}

// 配资信息弹窗样式
.loan-modal {
    width: 650rpx;
    max-height: 80vh;

    .form-item {
        margin-bottom: 30rpx;

        .form-label {
            font-size: 28rpx;
            color: #333;
            margin-bottom: 15rpx;
            display: block;
        }

        .amount-input {
            display: flex;
            align-items: center;
            border-bottom: 2rpx solid #eee;
            padding-bottom: 10rpx;

            .currency {
                font-size: 48rpx;
                color: #333;
                margin-right: 10rpx;
            }

            .amount-field {
                flex: 1;
                font-size: 48rpx;
                color: #333;
                border: none;
                outline: none;
            }
        }

        .picker-display {
            padding: 20rpx 0;
            border-bottom: 2rpx solid #eee;
            color: #333;
            font-size: 28rpx;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .text-input {
            width: 100%;
            padding: 20rpx 0;
            border-bottom: 2rpx solid #eee;
            font-size: 28rpx;
            color: #333;
            border: none;
            outline: none;
        }

        .bank-info {
            display: flex;
            align-items: center;
            padding: 20rpx 0;
            border-bottom: 2rpx solid #eee;

            .bank-name {
                color: #333;
                font-size: 28rpx;
                margin-right: 20rpx;
            }

            .bank-account {
                color: #333;
                font-size: 28rpx;
                flex: 1;
            }

            .arrow {
                color: #999;
                font-size: 24rpx;
            }
        }
    }
}

.loan-modal-content {
    padding: 20rpx;
}

.amount-input-container {
    display: flex;
    align-items: center;
    padding: 14px;

    .currency {
        font-size: 24px;
        font-weight: bold;
        margin-right: 10px;
    }
}

:deep(.wd-action-sheet) {
    .wd-action-sheet__header {
        background-color: #f7f8fa;
    }

    .wd-action-sheet__item {
        font-size: 16px;
    }
}

:deep(.wd-cell__left) {
    flex: inherit !important;
}

.upload-cell-group {
    margin-top: 20rpx;

    .upload-container {
        padding: 20rpx;
        background: #fff;
    }
}
</style>
